/*
 * ShoppingCartModel.java
 * business
 *
 * Created by ChenTao on 2016/9/9.
 *
 * Copyright (c) 2016年 yidiandao. All rights reserved.
 */

package com.yidiandao.business.data.model;

import android.support.v4.util.ArrayMap;

import com.yidiandao.business.constant.Preferences;
import com.yidiandao.business.constant.ServerCode;
import com.yidiandao.business.constant.Urls;
import com.yidiandao.business.data.bean.CartBean;
import com.yidiandao.business.data.bean.Discount;
import com.yidiandao.business.data.bean.FavourableInfo;
import com.yidiandao.business.data.bean.Goods;
import com.yidiandao.business.data.bean.Shop;
import com.yidiandao.business.data.event.RefreshShoppingCartEvent;
import com.yidiandao.business.data.net.BaseRequest;
import com.yidiandao.business.data.net.BaseResponse;
import com.yidiandao.business.data.net.NetBiz;
import com.yidiandao.business.data.net.NetListener;
import com.yidiandao.business.data.net.exception.BizErrorInfo;
import com.yidiandao.business.data.net.exception.NetErrorInfo;
import com.yidiandao.business.data.request.ChangeNumberByOneRequest;
import com.yidiandao.business.data.request.CheckServerStockAndPriceRequest;
import com.yidiandao.business.data.request.DeleteShoppingCartGoodsRequest;
import com.yidiandao.business.data.request.PostShoppingCartDataRequest;
import com.yidiandao.business.data.response.ChangeNumberByOneResponse;
import com.yidiandao.business.data.response.QueryShoppingCartListResponse;
import com.yidiandao.business.data.response.RecommendGoodsListResponse;
import com.yidiandao.business.manager.GiftManager;
import com.yidiandao.business.manager.ReduceManager;
import com.yidiandao.business.manager.ShoppingCartManager;
import com.yidiandao.business.ui.widget.listview.DisplayListItem;
import com.yidiandao.business.ui.widget.listview.Functional;
import com.yidiandao.business.ui.widget.listview.displaylistitem.ShoppingCartDividerListItem;
import com.yidiandao.business.ui.widget.listview.displaylistitem.ShoppingCartGoodsGiftListItem;
import com.yidiandao.business.ui.widget.listview.displaylistitem.ShoppingCartGoodsListItem;
import com.yidiandao.business.ui.widget.listview.displaylistitem.ShoppingCartGoodsReduceListItem;
import com.yidiandao.business.ui.widget.listview.displaylistitem.ShoppingCartInvalidClearListItem;
import com.yidiandao.business.ui.widget.listview.displaylistitem.ShoppingCartInvalidListItem;
import com.yidiandao.business.ui.widget.listview.displaylistitem.ShoppingCartOrderReduceListItem;
import com.yidiandao.business.ui.widget.listview.displaylistitem.ShoppingCartShopCarriageListItem;
import com.yidiandao.business.ui.widget.listview.displaylistitem.ShoppingCartShopListItem;
import com.yidiandao.business.utils.PreferenceUtils;
import com.yidiandao.business.utils.UIUtils;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * 购物车Model
 */
public class ShoppingCartModel implements IShoppingCartModel {

    private NetBiz mNetBiz = new NetBiz();

    private List<DisplayListItem> mShoppingCartListItems = new ArrayList<>();

    private ArrayMap<String, Integer> mShoppingCartGroupMap = new ArrayMap<>();

    @Override
    public void loadServerShoppingCartList(String tag, final OnLoadShoppingCartListListener listener) {

        BaseRequest request = new BaseRequest();
        request.setTag(tag);
        request.setUrl(Urls.CART_LIST);
        request.setToken(PreferenceUtils.getToken(UIUtils.getContext()));

        mNetBiz.sendGetRequest(request, QueryShoppingCartListResponse.class, new NetListener<QueryShoppingCartListResponse>() {
            @Override
            public void onSuccess(QueryShoppingCartListResponse response) {

                QueryShoppingCartListResponse.Data data = response.getData();

                mShoppingCartListItems.clear();
                mShoppingCartGroupMap.clear();

                // 创建一个失效商品的集合
                List<Goods> invalidGoodsList = new ArrayList<>();

                // 服务器购物车中的所有商品
                List<CartBean> cartList = data.getCartList();

                // ******** 同步购物车 *****************
                ShoppingCartManager.getInstance().initServerCartBeans(cartList);
                // ******** 同步赠品活动列表 *****************
                GiftManager.getInstance().clearAllFavourableInfoList();
                // ******** 同步减免活动列表 *****************
                ReduceManager.getInstance().clearAllReduce();

                if (cartList != null && cartList.size() != 0) {

                    // 解析失效的商品列表
                    parseInvalidGoodsList(invalidGoodsList, cartList);

                    // 解析服务器CartBean，并添加 店铺 商品列表，活动列表
                    for (int i = 0; i < cartList.size(); i++) {
                        parseServerCartBean(cartList.get(i));
                    }

                    // 添加没有库存的商品列表
                    if (invalidGoodsList.size() != 0) {
                        addInvalidGoodsListItems(invalidGoodsList);
                    }
                }

                // 从服务器拿数据时，先将购物车全选
                ShoppingCartManager.getInstance().selectAllGoodsOfShoppingCart(true);

                if (listener != null) {
                    listener.onSuccess(mShoppingCartListItems);
                }
            }

            @Override
            public boolean onError(NetErrorInfo netErrorInfo) {
                if (listener != null) {
                    listener.onFailed();
                }
                return true;
            }

            @Override
            public boolean onFailed(BizErrorInfo bizErrorInfo) {
                if (listener != null) {
                    listener.onFailed();
                }
                return true;
            }

            @Override
            public void onFinal() {
            }
        });
    }

    /**
     * 解析失效的商品列表
     */
    private void parseInvalidGoodsList(List<Goods> invalidGoodsList, List<CartBean> cartList) {
        Iterator<CartBean> cartBeanIterator = cartList.iterator();
        // 遍历购物车(店铺：商品列表)
        while (cartBeanIterator.hasNext()) {
            CartBean cartBean = cartBeanIterator.next();
            List<Goods> goodsList = cartBean.getGoodsList();
            Iterator<Goods> goodsIterator = goodsList.iterator();
            while (goodsIterator.hasNext()) {
                Goods goods = goodsIterator.next();
                if (goods.getStockNumber() == 0) {
                    // 没有库存了,将商品加入到失效商品列表
                    invalidGoodsList.add(goods);
                    // 没有库存了,将商品从购物车的列表移除掉
                    goodsIterator.remove();
                }
            }

            // 需要判断当前店铺中是否还有商品，如果没有，则将店铺也移除掉
            if (goodsList.size() == 0) {
                cartBeanIterator.remove();
            }
        }
    }

    /**
     * 解析失效的商品列表
     */
    private void addInvalidGoodsListItems(List<Goods> invalidGoodsList) {
        // 将失效的商品列表同步到购物车中
        ShoppingCartManager.getInstance().initInvalidGoodsList(invalidGoodsList);

        // 分割线
        mShoppingCartListItems.add(new ShoppingCartDividerListItem(null));
        List<DisplayListItem> invalidListItems = Functional.serverToClient(invalidGoodsList, new Functional.Processor<Goods, DisplayListItem>() {
            @Override
            public DisplayListItem processToClient(Goods goods) {
                return new ShoppingCartInvalidListItem(goods);
            }
        });
        // 失效商品
        mShoppingCartListItems.addAll(invalidListItems);
        // 清除失效商品
        mShoppingCartListItems.add(new ShoppingCartInvalidClearListItem(null));
    }

    /**
     * 对服务器给的CartBean进行转化处理
     */
    private void parseServerCartBean(CartBean cart) {

        // 单个商家
        // 商家信息,默认选中
        Shop shop = cart.getSupplier();
        shop.setEditMode(false);
        shop.setSelected(true);

        // 记录每一组的位置
        mShoppingCartGroupMap.put(shop.getSupplierId(), mShoppingCartListItems.size());

        // 添加店铺标题
        ShoppingCartShopListItem shopListItem = new ShoppingCartShopListItem(shop);
        mShoppingCartListItems.add(shopListItem);

        // 商家中的所有商品
        List<Goods> goodsList = cart.getGoodsList();

        for (Goods goods : goodsList) {

            // 每次从服务器刷新，默认为非编辑模式(显示修改商品数量的Menu)，
            goods.setEditMode(false);
            goods.setSelected(true);

            // 添加店铺商品
            mShoppingCartListItems.add(new ShoppingCartGoodsListItem(goods));

            // 对商品的活动进行处理
            FavourableInfo goodsFavourableInfo = goods.getFavourableInfo();
            if (goodsFavourableInfo != null) {
                // 商品有活动
                DisplayListItem goodsActiveListItem =
                        parseGoodsFavourableInfo(goods, goodsFavourableInfo);
                // 添加商品活动
                mShoppingCartListItems.add(goodsActiveListItem);
            }
        }

        // 订单的活动
        FavourableInfo orderFavourableInfo = shop.getFavourableInfo();
        if (orderFavourableInfo != null) {
            // 订单有活动
            DisplayListItem orderActiveListItem =
                    parseOrderFavourableInfo(shop, orderFavourableInfo);
            if (orderActiveListItem != null) {
                mShoppingCartListItems.add(orderActiveListItem);
            }
        }

        // 添加店铺运费
        // 由于是从服务器获取数据。且刷新时会选中所有的商品--->通过ShippingCartManager会计算出运费。所以totalLogisticsMoney有值

        if (shop.getLogisticsFreeMoney() != 0) {
            // 店铺设置了运费才显示，没设置就不显示
            mShoppingCartListItems.add(new ShoppingCartShopCarriageListItem(shop));
        }
    }

    /**
     * 解析购物车单个商品的活动
     */
    private DisplayListItem parseGoodsFavourableInfo(Goods goods, FavourableInfo favourableInfo) {
        // 设置当前活动属于商品活动
        favourableInfo.setBelongGoods(goods);
        favourableInfo.setBelongType(FavourableInfo.BELONG_GOODS);

        // 单个商品活动
        // 当前商品的活动类型
        String type = favourableInfo.getType();
        if (FavourableInfo.TYPE_DERATE.equals(type)) {
            // **** 添加到满减活动列表 ******************
            ReduceManager.getInstance().addReduceFavourableInfo(favourableInfo);

            // 单商品满减满减活动
            return new ShoppingCartGoodsReduceListItem(favourableInfo);
        } else {
            // 满赠、加价购活动 --> 赠送 赠品
            setDefaultGiftOfGoods(favourableInfo);

            // 单商品满赠活动
            // ********** 赠品活动添加到GiftManager ***************
            GiftManager.getInstance().addGiftFavourableInfo(favourableInfo);

            return new ShoppingCartGoodsGiftListItem(favourableInfo);
        }
    }

    /**
     * 针对单商品满赠/加价购活动，设置默认的赠品
     */
    private void setDefaultGiftOfGoods(FavourableInfo favourableInfo) {
        // 判断有没有满足赠品的选择条件，如果满足，则默认选择第一个赠品
        List<Goods> giftList = favourableInfo.getGiftList();
        if (giftList.size() != 0) {
            Goods firstGift = giftList.get(0);
            if (firstGift.getGoodsPrice() == 0) {
                // 第一个赠品价格为0 -->
                // 默认选中第一个赠品（如果是加价购，默认不选择）,同时设置当前赠品为选中状态，方便在赠品选择列表显示
                firstGift.setSelected(true);
                favourableInfo.setChooseGift(firstGift);
            }
        }
    }

    /**
     * 解析购物车店铺订单的活动
     */
    private DisplayListItem parseOrderFavourableInfo(Shop shop, FavourableInfo favourableInfo) {
        // 设置当前 活动 所属的 店铺
        favourableInfo.setBelongShop(shop);
        favourableInfo.setBelongType(FavourableInfo.BELONG_ORDER);

        // 活动的类型
        String type = favourableInfo.getType();
        if (FavourableInfo.TYPE_ORDER_DERATE.equals(type)) {

            // 由于初始化时，店铺的所有商品已经选择，
            // 因此，只需要判断 discountList 里面有没有内容，有内容则默认取第一个即可。没有内容内容则说明未达选择条件
            setDefaultDiscountOfOrder(favourableInfo);

            // **** 添加到满减活动列表
            ReduceManager.getInstance().addReduceFavourableInfo(favourableInfo);

            // 订单满减活动
            return new ShoppingCartOrderReduceListItem(favourableInfo);
        }

        // todo 订单满赠活动暂时不做
        return null;
    }

    /**
     * 设置订单满减活动的减免信息
     */
    private void setDefaultDiscountOfOrder(FavourableInfo favourableInfo) {
        List<Discount> discountList = favourableInfo.getDiscountList();
        if (discountList.size() == 0) {
            favourableInfo.setBestDiscount(null);
        } else {
            Discount firstDiscount = discountList.get(0);
            favourableInfo.setBestDiscount(firstDiscount);
        }
    }

    @Override
    public void changeNumberByOne(
            final Goods goods, String tag, final OnUpdateShoppingCartCountListener listener) {

        ChangeNumberByOneRequest request = new ChangeNumberByOneRequest();
        request.setUrl(Urls.CHANGE_NUMBER_BY_ONE);
        request.setTag(tag);
        request.setToken(PreferenceUtils.getToken(UIUtils.getContext()));
        request.setRecId(goods.getRecId());
        request.setGoodsNumber(goods.getNumberHelper() + "");

        mNetBiz.sendGetRequest(request, ChangeNumberByOneResponse.class,
                new NetListener<ChangeNumberByOneResponse>() {
                    @Override
                    public void onSuccess(ChangeNumberByOneResponse response) {
                        ChangeNumberByOneResponse.Data data = response.getData();

                        // 必须更新DisplayListItem中绑定的数据
                        // 在loadServerCartList中之所以两者分开可以，因为处理的是同一个对象。而在这里对象已经是新对象
                        // 即使计算的数据没有问题，但Ui仍然不会发生任何改变（displayListItem的选中的状态，与联动状态）

                        // 当前商品所属店铺的购物车信息
                        CartBean cartInfo = data.getCartInfo();

                        // 更新购物车对应店铺订单信息
                        ShoppingCartManager.getInstance().updateCartInfo(cartInfo);

                        Shop updateShop = cartInfo.getSupplier();
                        List<Goods> updateGoodsList = cartInfo.getGoodsList();

                        // --------------------------- 更新DisplayListItem
                        // --------------------------------
                        // --------------------- 同时更新DisplayListItem 绑定的数据 ------------------------

                        // 原来的ListItem
                        int groupIndex = mShoppingCartGroupMap.get(updateShop.getSupplierId());
                        updateShopListItem(mShoppingCartListItems.get(groupIndex), updateShop);

                        // 更新商家中的所有商品
                        for (Goods updateGoods : updateGoodsList) {

                            groupIndex++;
                            updateGoodsListItem(
                                    mShoppingCartListItems.get(groupIndex), updateGoods, goods);

                            // 对商品的活动进行处理
                            FavourableInfo goodsFavourableInfo = updateGoods.getFavourableInfo();
                            if (goodsFavourableInfo != null) {

                                // 原来的ListItem
                                groupIndex++;
                                updateGoodsFavourableListItem(
                                        mShoppingCartListItems.get(groupIndex),
                                        updateGoods,
                                        goodsFavourableInfo);
                            }
                        }

                        // 重新当前计算店铺中的所有商品是否选中
                        boolean allGoodsOfShopSelected =
                                ShoppingCartManager.getInstance()
                                        .isAllGoodsOfShopSelected(updateShop);
                        updateShop.setSelected(allGoodsOfShopSelected);

                        // 更新订单的活动
                        FavourableInfo orderFavourableInfo = updateShop.getFavourableInfo();
                        if (orderFavourableInfo != null) {
                            groupIndex++;
                            updateShopFavourableListItem(
                                    mShoppingCartListItems.get(groupIndex),
                                    updateShop,
                                    orderFavourableInfo);
                        }

                        // 更新店铺的运费
                        groupIndex++;
                        try {
                            mShoppingCartListItems.get(groupIndex);
                            updateShopCarriageListItem(
                                    mShoppingCartListItems.get(groupIndex), updateShop);
                        } catch (IndexOutOfBoundsException e) {
                            // 由于店铺运费可能不显示，所有此处可能会有异常抛出
                        }

                        if (listener != null) {
                            listener.onSuccess();
                        }
                    }

                    @Override
                    public boolean onError(NetErrorInfo netErrorInfo) {
                        if (listener != null) {
                            listener.onFailed();
                        }
                        return false;
                    }

                    @Override
                    public boolean onFailed(BizErrorInfo bizErrorInfo) {
                        if (listener != null) {
                            listener.onFailed();
                        }
                        return true;
                    }

                    @Override
                    public void onFinal() {
                        if (listener != null) {
                            listener.onFinal();
                        }
                    }
                });
    }

    @Override
    public void postShoppingCartData(String pagerTag, String recJson, String favourableJson, final OnShoppingCartOperatorListener listener) {

        PostShoppingCartDataRequest request = new PostShoppingCartDataRequest();
        request.setTag(pagerTag);
        request.setUrl(Urls.POST_SHOPPING_CART_DATA);
        request.setToken(PreferenceUtils.getToken(UIUtils.getContext()));
        request.setRecJson(recJson);
        request.setFavourableJson(favourableJson);

        mNetBiz.sendPostRequest(request, BaseResponse.class, new NetListener<BaseResponse>() {
            @Override
            public void onSuccess(BaseResponse response) {
                if (listener != null) {
                    listener.onSuccess();
                }
            }

            @Override
            public boolean onError(NetErrorInfo netErrorInfo) {
                if (listener != null) {
                    listener.onFailed();
                }
                return true;
            }

            @Override
            public boolean onFailed(BizErrorInfo bizErrorInfo) {
                if (listener != null) {
                    listener.onFailed();
                }
                return true;
            }

            @Override
            public void onFinal() {

            }
        });
    }

    /**
     * 更新当前店铺运费信息
     */
    private void updateShopCarriageListItem(DisplayListItem displayListItem, Shop updateShop) {
        // 替换DisplayListItem的数据
        if (displayListItem instanceof ShoppingCartShopCarriageListItem) {
            ShoppingCartShopCarriageListItem shopCarriageListItem =
                    (ShoppingCartShopCarriageListItem) displayListItem;

            // 重新计算当前店铺的运费
            ShoppingCartManager.getInstance().calculateShopCarriage(updateShop);

            shopCarriageListItem.setContentData(updateShop);
        }
    }

    /**
     * 更新对应的ShopListItem的数据
     */
    private void updateShopListItem(DisplayListItem displayListItem, Shop updateShop) {
        // 替换DisplayListItem中的数据
        if (displayListItem instanceof ShoppingCartShopListItem) {
            ShoppingCartShopListItem shopListItem = (ShoppingCartShopListItem) displayListItem;
            // 更新为非编辑状态状态
            updateShop.setEditMode(false);
            shopListItem.setContentData(updateShop);
        }
    }

    /**
     * 更新对应的GoodsListItem
     */
    private void updateGoodsListItem(
            DisplayListItem displayListItem, Goods updateGoods, Goods goods) {
        // 添加店铺商品
        if (displayListItem instanceof ShoppingCartGoodsListItem) {
            ShoppingCartGoodsListItem goodsListItem = (ShoppingCartGoodsListItem) displayListItem;
            Goods originGoods = goodsListItem.getContentData();
            updateGoods.setEditMode(false);
            // 如果当前商品是编辑的商品
            if (goods.equals(originGoods)) {
                // 选中当前编辑的商品
                updateGoods.setSelected(true);

                // 切换数量时 刷新ShoppingCartManager中统计的商品价格
                ShoppingCartManager.getInstance().updateGoodsCount(updateGoods);

            } else {
                // 非当前编辑的商品则保留之前的状态
                updateGoods.setSelected(originGoods.isSelected());
            }
            goodsListItem.setContentData(updateGoods);
        }
    }

    /**
     * 更新对应单商品活动ListItem
     */
    private void updateGoodsFavourableListItem(
            DisplayListItem goodsFavourableListItem,
            Goods updateGoods,
            FavourableInfo goodsFavourableInfo) {

        // 设置当前活动属于商品活动
        goodsFavourableInfo.setBelongGoods(updateGoods);
        goodsFavourableInfo.setBelongType(FavourableInfo.BELONG_GOODS);

        // 单个商品活动
        // 当前商品的活动类型
        String type = goodsFavourableInfo.getType();
        if (FavourableInfo.TYPE_DERATE.equals(type)) {
            // 单品满减活动

            // 更新商品满减活动列表
            ReduceManager.getInstance().updateReduceInfo(goodsFavourableInfo);

            // 更新Ui
            if (goodsFavourableListItem instanceof ShoppingCartGoodsReduceListItem) {
                ((ShoppingCartGoodsReduceListItem) goodsFavourableListItem)
                        .setContentData(goodsFavourableInfo);
            }

        } else {
            // 满赠、加价购活动
            // 选择默认的赠品
            setDefaultGiftOfGoods(goodsFavourableInfo);

            // 更新单商品满赠/加价购活动
            GiftManager.getInstance().updateGiftInfo(goodsFavourableInfo);

            // 更新UI
            if (goodsFavourableListItem instanceof ShoppingCartGoodsGiftListItem) {
                ((ShoppingCartGoodsGiftListItem) goodsFavourableListItem)
                        .setContentData(goodsFavourableInfo);
            }
        }
    }

    /**
     * 更新订单对应活动的ListItem
     */
    private void updateShopFavourableListItem(
            DisplayListItem orderFavourableListItem,
            Shop updateShop,
            FavourableInfo orderFavourableInfo) {

        // 设置当前 活动 所属的 店铺
        orderFavourableInfo.setBelongShop(updateShop);
        orderFavourableInfo.setBelongType(FavourableInfo.BELONG_ORDER);

        // 活动的类型
        String type = orderFavourableInfo.getType();
        if (FavourableInfo.TYPE_ORDER_DERATE.equals(type)) {

            // 由于初始化时，店铺的所有商品已经选择，
            // 因此，只需要判断 discountList 里面有没有内容，有内容则默认取第一个即可。没有内容内容则说明未达选择条件
            setDefaultDiscountOfOrder(orderFavourableInfo);

            // 更新订单满减活动
            ReduceManager.getInstance().updateReduceInfo(orderFavourableInfo);

            // 订单满减活动
            if (orderFavourableListItem instanceof ShoppingCartOrderReduceListItem) {
                ((ShoppingCartOrderReduceListItem) orderFavourableListItem)
                        .setContentData(orderFavourableInfo);
            }
        }
        // todo 订单满赠活动暂时不做
    }

    @Override
    public void deleteGoodsFromServer(
            String allGoodsCatIds, String tag, final OnShoppingCartOperatorListener listener) {

        DeleteShoppingCartGoodsRequest request = new DeleteShoppingCartGoodsRequest();
        request.setToken(PreferenceUtils.getToken(UIUtils.getContext()));
        request.setUrl(Urls.DELETE_GOODS_OF_CART);
        request.setTag(tag);
        request.setRecId(allGoodsCatIds);

        mNetBiz.sendGetRequest(
                request,
                BaseResponse.class,
                new NetListener<BaseResponse>() {
                    @Override
                    public void onSuccess(BaseResponse response) {
                        if (listener != null) {
                            listener.onSuccess();
                        }
                    }

                    @Override
                    public boolean onError(NetErrorInfo netErrorInfo) {
                        if (listener != null) {
                            listener.onFailed();
                        }
                        return true;
                    }

                    @Override
                    public boolean onFailed(BizErrorInfo bizErrorInfo) {
                        if (listener != null) {
                            listener.onFailed();
                        }
                        return true;
                    }

                    @Override
                    public void onFinal() {
                    }
                });
    }

    @Override
    public void checkServerStockAndPrice(
            String tag,
            String goodsNumberAndPriceJson,
            final OnShoppingCartCheckStockAndPriceListener listener) {

        // 检查服务器的库存
        CheckServerStockAndPriceRequest request = new CheckServerStockAndPriceRequest();
        request.setToken(PreferenceUtils.getToken(UIUtils.getContext()));
        request.setUrl(Urls.BALANCE_CART);
        request.setTag(tag);
        request.setRecJson(goodsNumberAndPriceJson);
        request.setCheck(CheckServerStockAndPriceRequest.CHECK_SERVER_STOCK_AND_PRICE);

        mNetBiz.sendPostRequest(
                request,
                BaseResponse.class,
                new NetListener<BaseResponse>() {
                    @Override
                    public void onSuccess(BaseResponse baseResponse) {
                        if (listener != null) {
                            listener.onSuccess();
                        }
                    }

                    @Override
                    public boolean onError(NetErrorInfo netErrorInfo) {
                        if (listener != null) {
                            listener.onFailed();
                        }
                        return true;
                    }

                    @Override
                    public boolean onFailed(BizErrorInfo bizErrorInfo) {

                        // 库存不足
                        if (bizErrorInfo.getCode()
                                == ServerCode.ShoppingCartStock.STOCK_OR_PRICE_CHANGED) {
                            if (listener != null) {
                                listener.onStockNotEnoughOrPriceChanged(bizErrorInfo.getMessage());
                            }
                            return false;
                        }

                        if (listener != null) {
                            listener.onFailed();
                        }
                        return true;
                    }

                    @Override
                    public void onFinal() {
                    }
                });
    }

    @Override
    public void postRefreshShoppingCartState(boolean refreshShoppingCart) {
        RefreshShoppingCartEvent refreshShoppingCartEvent = new RefreshShoppingCartEvent();
        refreshShoppingCartEvent.setRefreshShoppingCart(refreshShoppingCart);
        EventBus.getDefault().post(refreshShoppingCartEvent);
    }

    @Override
    public void loadShoppingCartRecommendGoods(
            String tag, final OnLoadRecommendGoodsListener listener) {
        BaseRequest request = new BaseRequest();
        request.setUrl(Urls.SHOPPING_CART_RECOMMEND_GOODS);
        request.setTag(tag);
        request.setToken(PreferenceUtils.getToken(UIUtils.getContext()));
        mNetBiz.sendGetRequest(request, RecommendGoodsListResponse.class,
                new NetListener<RecommendGoodsListResponse>() {
                    @Override
                    public void onSuccess(RecommendGoodsListResponse response) {
                        if (listener != null) {
                            listener.onSuccess(response.getData());
                        }
                    }

                    @Override
                    public boolean onError(NetErrorInfo netErrorInfo) {
                        if (listener != null) {
                            listener.onFailed();
                        }
                        return false;
                    }

                    @Override
                    public boolean onFailed(BizErrorInfo bizErrorInfo) {
                        if (listener != null) {
                            listener.onFailed();
                        }
                        return false;
                    }

                    @Override
                    public void onFinal() {
                    }
                });
    }

    @Override
    public boolean needRefreshShoppingCart() {
        return PreferenceUtils.getBoolean(
                UIUtils.getContext(), Preferences.REFRESH_SHOPPING_CART, true, true);
    }

    @Override
    public void setNeedRefreshShoppingCart(boolean refreshShoppingCart) {
        PreferenceUtils.setBoolean(
                UIUtils.getContext(), Preferences.REFRESH_SHOPPING_CART, refreshShoppingCart, true);
    }
}
